package com.jerry.boot.business.common;

import cn.hutool.core.io.FileUtil;
import com.jerry.boot.business.auth.pojo.AuthDto;
import com.jerry.boot.business.file.pojo.FileDto;
import com.jerry.boot.business.user.User;
import com.jerry.boot.business.user.UserService;
import com.jerry.boot.core.JConstant;
import com.jerry.boot.core.base.JConfigureProperties;
import com.jerry.boot.core.web.ServletContextHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;

@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    private UserService userService;

    @Resource
    private JConfigureProperties jConfigureProperties;

    @Override
    public User getLoginUser() {
        HttpSession session = ServletContextHelper.getSession();
        AuthDto authDto = (AuthDto) session.getAttribute(JConstant.AUTH_USER_KEY);
        String username = authDto.getUsername();
        return userService.getUserByUsername(username);
    }

    @Override
    public void copyFile2AvatarFile(FileDto fileDto) {
        String avatarPath = jConfigureProperties.getAvatarPath();
        File dir = new File(avatarPath);
        FileUtil.mkdir(dir);
        File file = FileUtil.file(fileDto.getFilePath());
        if (FileUtil.exist(file)) {
            FileUtil.copyFile(file, dir);
        }
    }
}
